package com.hmdp.interceptor;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.hmdp.dto.UserDTO;
import com.hmdp.utils.UserHolder;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.LOGIN_USER_KEY;
import static com.hmdp.utils.RedisConstants.LOGIN_USER_TTL;

/**
 * ClassName: RefreshTokenIntercepter
 * Package: IntelliJ IDEA
 * Description:
 * Written by HanXu
 * Create 2024.09.24 0:12
 */
public class RefreshTokenIntercepter implements HandlerInterceptor{

    private StringRedisTemplate stringRedisTemplate;

    //在MvcConfig中注入，然后传参
    public RefreshTokenIntercepter(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    //前置拦截器
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //获取token
        String authorization = request.getHeader("authorization");

        //用token获取在redis中的用户hash
        if(StrUtil.isBlank(authorization)){
            return true;
        }
        Map userDTOMap = stringRedisTemplate.opsForHash().entries(LOGIN_USER_KEY + authorization);

        if(userDTOMap.isEmpty()){
            return true;
        }
        //用户hash转为UserDTO对象
        UserDTO user = BeanUtil.fillBeanWithMap(userDTOMap, new UserDTO(), false);

        //保存用户到ThreadLocal
        UserHolder.saveUser(user);

        //刷新token有效期
        stringRedisTemplate.expire(LOGIN_USER_KEY + authorization, LOGIN_USER_TTL, TimeUnit.MINUTES);

        //放行
        return true;
    }


    //后置拦截器
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
